package com.cloudbroker.bcs.platform.ltb.middle.extservice.sms.impl;

import com.alibaba.fastjson.JSONArray;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.csvc.sms.api.constants.SMSErrorCodes;
import com.cloudbroker.bcs.csvc.sms.api.constants.SMSFields;
import com.cloudbroker.bcs.csvc.sms.api.t2service.SMST2Service;
import com.cloudbroker.bcs.platform.ltb.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.ltb.common.constant.SmsPriority;
import com.cloudbroker.bcs.platform.ltb.common.constant.SysContants;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.sms.SMSExtService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuyn15828 on 2016/3/15.
 */
@Service
public class SMSExtServiceImpl implements SMSExtService {
    @Resource
    private SMST2Service smsServiceT2;

    private static final int SEND_MESSAGE_SINGLE = 1;
    private static final int SEND_MESSAGE_BATCH = 2;
    private static final Logger logger = LoggerFactory.getLogger(SMSExtService.class);

    @Override
    public String sendMessage(String mobile, String content) {
        return sendMessage(mobile , content , SmsPriority.NORMAL);
    }

    @Override
    public String sendMessage(String mobile, String content, SmsPriority priority) {
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put(SMSFields.MOBILE_TEL , mobile);
        reqMap.put(SMSFields.SMS_CONTENT , content);
        reqMap.put(SMSFields.SMS_PRIORITY , priority.getValue());
        return doSendSMSFromChannel(reqMap , SEND_MESSAGE_SINGLE);
    }

    @Override
    public JSONArray sendMessage(String content, String... mobiles) {
        return sendMessage(content , SmsPriority.NORMAL , mobiles);
    }

    @Override
    public JSONArray sendMessage(String content, SmsPriority priority, String... mobiles) {
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put(SMSFields.MOBILE_TEL_STR , StringUtils.join(mobiles , ","));
        reqMap.put(SMSFields.SMS_CONTENT , content);
        reqMap.put(SMSFields.SMS_PRIORITY , priority.getValue());
        return JSONArray.parseArray(doSendSMSFromChannel(reqMap , SEND_MESSAGE_BATCH));
    }

    @Override
    public boolean sendMail(String emailTo, String emailContent) {
        return sendMail(emailTo , emailContent , SmsPriority.NORMAL);
    }

    @Override
    public boolean sendMail(String emailTo, String emailContent, SmsPriority priority) {
        return sendMail(emailTo , null , emailContent , priority);
    }

    @Override
    public boolean sendMail(String emailTo, String emailSubject, String emailContent) {
        return sendMail(emailTo , emailSubject , emailContent , SmsPriority.NORMAL);
    }

    @Override
    public boolean sendMail(String emailTo, String emailSubject, String emailContent, SmsPriority priority) {
        return sendMail(emailTo , null , null , emailSubject , emailContent , priority);
    }

    @Override
    public boolean sendMail(String emailTo, String emailCc, String emailBcc,
                            String emailSubject, String emailContent) {
        return sendMail(emailTo , emailCc , emailBcc , emailSubject , emailContent , SmsPriority.NORMAL);
    }

    @Override
    public boolean sendMail(String emailTo, String emailCc, String emailBcc,
                            String emailSubject, String emailContent, SmsPriority priority) {
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put(SMSFields.EMAIL_TO , emailTo);
        reqMap.put(SMSFields.EMAIL_TEXT , emailContent);
        reqMap.put(SMSFields.EMAIL_PRIORITY , priority.getValue());
        if( StringUtils.isNotEmpty(emailCc) ) {
            reqMap.put(SMSFields.EMAIL_CC , emailCc);
        }
        if( StringUtils.isNotEmpty(emailCc) ) {
            reqMap.put(SMSFields.EMAIL_BCC , emailBcc);
        }
        if( StringUtils.isNotEmpty(emailCc) ) {
            reqMap.put(SMSFields.EMAIL_SUBJECT , emailSubject);
        }
        return doSendMailFromChannel(reqMap);
    }

    private boolean doSendMailFromChannel(Map<String, Object> reqMap) {
        String mailImpl = ConfigValues.getMailImpl();
        if(SysContants.CONFIG_SMS_IMPL.equalsIgnoreCase(mailImpl) && ConfigValues.getItnregistrTokenSwich()) {
            addSMSServiceImplConfig(reqMap);
            Map<String, Object> sendResult = null;
            try {
                sendResult = smsServiceT2.sendMail(reqMap);
            } catch (Exception e) {
                logger.error("send mail failed", e);
            }
            return SMSErrorCodes.isSuccess(sendResult);
        }
        return true;
    }

    private String doSendSMSFromChannel(Map<String,Object> reqMap , Integer sendType) {
        String smsImpl = ConfigValues.getSMSImpl();
        logger.info("=======> sms.impl = " + smsImpl );
        logger.info("=======> itn.impl = " + ConfigValues.getItnregistrTokenSwich() );
        if(SysContants.CONFIG_SMS_IMPL.equalsIgnoreCase(smsImpl) && ConfigValues.getItnregistrTokenSwich()) {
            addSMSServiceImplConfig(reqMap);
            Map<String, Object> sendResult = null;
            try {
                if( sendType.equals(SEND_MESSAGE_SINGLE) ) {
                    sendResult = smsServiceT2.sendSingle(reqMap);
                } else if( sendType.equals(SEND_MESSAGE_BATCH) ) {
                    sendResult = smsServiceT2.sendBatch(reqMap);
                }
            } catch (Exception e) {
                logger.error("send SMS failed", e);
            }
            if (SMSErrorCodes.isSuccess(sendResult)) {
                return ValueUtil.getString(sendResult.get(SMSFields.SMS_ID), "");
            }
            return null;
        }
        return StringUtil.EMPTY_STRING;
    }

    private void addSMSServiceImplConfig(Map<String, Object> reqMap) {
        reqMap.put(SMSFields.SMS_IMPL, ConfigValues.getSMSImpl());
        reqMap.put(SMSFields.SMS_SVC_URL , ConfigValues.getSMSSvcUrl());
        reqMap.put(SMSFields.MAIL_IMPL , ConfigValues.getMailImpl());
        reqMap.put(SMSFields.MAIL_SVC_URL , ConfigValues.getMailSvcUrl());
        reqMap.put(SMSFields.OWN_COMPANY_ID , ConfigValues.getSmsOwnCompanyId());
        reqMap.put(SMSFields.COMPANY_ID , ConfigValues.getSmsCompanyId());
        reqMap.put(SMSFields.BUSINSYS_NO , ConfigValues.getSmsBusinsysNo());
        reqMap.put(SMSFields.SMS_AUTHKEY , ConfigValues.getSmsAuthKey());
    }
}
